<?php
class SummaryItemsHelper {

	/**
	 * 取采购需求汇总明细
	 */
	static function getBySummary($summary_id, $where=null){
		return Db::get('SummaryItems')->select('*,price*amount AS total')
					->where(array('summary_id'=>$summary_id), $where)
					->order('sno ASC,demand_type ASC')->getAll();
		//此处不能加hkey()，因SummaryItems是汇总表，相同材料记录可能有多条;
		//请使用getBySummaryToIndent取无重复的材料列表
	}

	static function getBySummaryToIndent($summary_id, $where=null){
		return Db::get('SummaryItems')
					->select('t0.*, t1.name as supplier_name, SUM(t0.amount) AS amount')
					->join('Supplier')->on('t0.supplier_id=t1.id')
					->where(array('summary_id'=>$summary_id), $where)
					->group('ware_id')->hkey('ware_id')
					->order('supplier_id ASC, sno ASC, demand_type ASC')->getAll();
	}

	/**
	 * 按采购类型，切分指定汇总需求列表
	 */
	static function splitbyDemandType($items){
		$tmp = array();
		foreach($items as $item){
			if(!isset($tmp[$item['ware_id']])){
				$tmp[$item['ware_id']] = array_intersect_key($item, array_flip(array(
					'ware_id','class_id','class_path','sno','name','brand','specific','unit','summary_id',
					'supplier_id', 'price', 'quote_time', )));
				$tmp[$item['ware_id']]['amount'] = 0;
				$tmp[$item['ware_id']]['total'] = 0;
				$tmp[$item['ware_id']]['list'] = array();
			}
			$list =& $tmp[$item['ware_id']]['list'];
			if(!isset($list[$item['dept_id']])){
				$list[$item['dept_id']] = array('name'=>$item['dept_name']);
			}
			$list[$item['dept_id']][$item['demand_type']] = array_intersect_key($item,
					array_flip( array('amount', 'demand_type', 'dept_id', 'sum_month', 'dept_name') ));
			$tmp[$item['ware_id']]['amount'] += $item['amount'];
			$tmp[$item['ware_id']]['total'] += $item['total'];
		}
		return $tmp;
	}

	/**
	 * 修改SummaryItems.state字段
	 * SummaryItems由DemandItems生成的视图，直接修改SummaryItems字段内容是不允许的(有Group By)
	 * 这里提供修改SummaryItems字段内容的方法，是使用了DemandItems对象
	 */
	static function changeState($id, $where, $state, $feedback=''){
		return Db::get('_DemandItems')->update(array('state'=>$state, 'feedback'=>$feedback))
								->where(array('summary_id'=>$id), $where)->exec();
	}
	
}
?>
